<template>
  <div class="createPost-container">
    <div class="sticky-container">
      <el-button v-if="Number(type) === 1" v-loading="loading" type="primary" @click="updateDevice">
        保存
      </el-button>
    </div>
    <div class="createPost-main-container">
      <div class="title-container">详情信息:</div>
      <div class="table-container">
        <div class="table-item">
          <div class="item-label">设备名称</div>
          <el-input v-model="detail.name" />
        </div>
        <div class="table-item">
          <div class="item-label">ip</div>
          <el-input v-model="detail.ip" />
        </div>
        <div class="table-item">
          <div class="item-label">通道</div>
          <el-select
            v-model="detail.channel"
          >
            <el-option
              v-for="item in channels"
              :key="item.key"
              :label="item.label"
              :value="item.key"
            />
          </el-select>
        </div>
        <div class="table-item">
          <div class="item-label">通道标识</div>
          <el-select
            v-model="detail.channelFlag"
          >
            <el-option
              v-for="item in channelTypes"
              :key="item.key"
              :label="item.label"
              :value="item.key"
            />
          </el-select>
        </div>
        <div class="table-item">
          <div class="item-label">状态</div>
          <el-input :value="detail.onlineStatus ? '在线' : '离线'" disabled readonly />
        </div>
        <div class="table-item">
          <div class="item-label">设备型号</div>
          <el-input v-model="detail.deviceModel" disabled readonly />
        </div>
        <div class="table-item">
          <div class="item-label">mac</div>
          <el-input v-model="detail.mac" disabled readonly />
        </div>
        <div class="table-item">
          <div class="item-label">固件版本</div>
          <el-input v-model="detail.firmwareVersion" disabled readonly />
        </div>
        <div class="table-item">
          <div class="item-label">Uboot版本</div>
          <el-input v-model="detail.ubootVersion" disabled readonly />
        </div>
      </div>
      <div class="title-container">
        绑定人员:
        <el-button
          v-if="Number(type) === 1"
          type="primary"
          style="margin-left:10px"
          @click="onIssue(detail.id)"
        >
          下发
        </el-button>
      </div>
      <MemberList :data="detail.deviceUserList" />

      <div class="title-container">打卡记录:</div>
      <List :data="detail.reportLog" />
    </div>

    <el-dialog title="下发" width="440px" :visible.sync="issueVisible">
      <div class="face-container">
        <div
          v-for="item in memberList"
          :key="item.id"
          class="box-container"
          @click="onChange(item.uid)"
        >
          <el-avatar shape="square" :size="76" fit="cover" :src="item.faceImg">
            <img src="@/assets/error.png">
          </el-avatar>
          <div class="text-container">
            <div>{{ item.name }}</div>
            <div>{{ item.uid }}</div>
          </div>

          <div class="check-box">
            <el-checkbox
              :value="actions.includes(item.uid)"
              style="pointer-events: none"
            />
          </div>
        </div>
      </div>

      <pagination
        v-show="memberTotal > 0"
        :total="memberTotal"
        :page.sync="memberQuery.current"
        :limit.sync="memberQuery.size"
        style="padding: 0"
        @pagination="fetchList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="issueVisible = false">
          {{ $t("table.cancel") }}
        </el-button>
        <el-button
          type="primary"
          @click="onSave"
        >
          {{ $t("table.confirm") }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import List from './List'
import MemberList from './MemberList'
import { getInfo, syncUsetToDevice, updateDevice } from '@/api/device'
import { fetchList } from '@/api/member'
import Pagination from '@/components/Pagination'
import channels from './mixins/channels'

export default {
  name: 'MemberDetail',
  components: {
    MemberList,
    List,
    Pagination
  },
  mixins: [channels],
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      tempRoute: {},
      detail: {},
      issueVisible: false,
      memberList: [],
      memberTotal: 0,
      memberQuery: {
        current: 1,
        size: 10
      },
      actions: [],
      deviceId: '',
      channelTypes: [
        {
          key: 1,
          label: '上班打卡'
        },
        {
          key: 2,
          label: '通道打卡'
        }
      ],
      loading: false
    }
  },
  computed: {
    ...mapGetters([
      'type'
    ]),
    lang() {
      return this.$store.getters.language
    }
  },
  created() {
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      this.fetchData(id)
    }

    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    fetchData(id) {
      getInfo({ id })
        .then((response) => {
          this.detail = response.object || {}

          // set tagsview title
          this.setTagsViewTitle()

          // set page title
          this.setPageTitle()
        })
        .catch((err) => {
          console.log(err)
        })
    },
    setTagsViewTitle() {
      const title = this.lang === 'zh' ? '设备详情' : '设备详情'
      const route = Object.assign({}, this.tempRoute, {
        title: `${title}`
      })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    setPageTitle() {
      const title = '设备详情'
      document.title = `${title}`
    },
    fetchList() {
      fetchList(this.memberQuery).then((response) => {
        const { records, total } = response.object
        this.memberList = records || []
        this.memberTotal = total
      })
    },
    onIssue(id) {
      this.deviceId = id
      this.issueVisible = true
      this.fetchList()
    },
    onChange(id) {
      const index = this.actions.indexOf(id)
      if (index > -1) {
        this.actions.splice(index, 1)
        return
      }
      if (this.actions.length > 5) {
        return this.$message.error('最多选择6个')
      }
      this.actions.push(id)
    },
    onSave() {
      if (this.actions.length === 0) {
        return this.$message.error('请选择人脸')
      }
      const formData = new FormData()
      formData.append('deviceId', this.deviceId)
      formData.append('uids', this.actions)
      syncUsetToDevice(formData).then(() => {
        this.issueVisible = false
        this.$notify({
          title: '成功',
          message: '下发成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    updateDevice() {
      const data = {
        id: this.detail.id,
        name: this.detail.name,
        channel: this.detail.channel,
        type: this.detail.channelFlag,
        ip: this.detail.ip
      }
      if (this.loading) return
      this.loading = true
      updateDevice(data).then(() => {
        this.loading = false
        this.$notify({
          title: '成功',
          message: '修改成功',
          type: 'success',
          duration: 2000
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 12px 20px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .sticky-container {
    padding: 10px 20px;
    text-align: right;
  }

  .title-container {
    font-size: 20px;
    font-weight: 600;
    margin: 20px 0;
  }

  .table-container {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
  }

  .table-item {
    width: 200px;
  }

  .item-label {
    color: #909399;
    margin-bottom: 5px;
    font-weight: 600;
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
  .face-container {
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
  }
  .box-container {
    position: relative;
    width: 76px;
    height: 76px;
    border-radius: 5px;
    overflow: hidden;
    background: #f5f5f5;
    cursor: pointer;
  }
  .el-avatar {
    display: flex;
    align-items: center;
    justify-content: center;
  }
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  .check-box {
    position: absolute;
    top: 4px;
    right: 4px;
  }
  .text-container {
    position: absolute;
    bottom: 0px;
    left: 0;
    width: 100%;
    padding: 4px 0;
    text-align: center;
    background: rgba(0, 0, 0, 0.1);
    color: #fff;
    backdrop-filter: blur(6px);
    font-size: 12px;
  }
}
</style>
